package com.imooc.luckymoney.handle;

import com.imooc.luckymoney.domain.Result;
import com.imooc.luckymoney.enums.ResultEnum;
import com.imooc.luckymoney.exception.LuckymoneyException;
import com.imooc.luckymoney.util.ResultUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * 在spring 3.2中，新增了@ControllerAdvice 注解，
 * 可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute，并应用到所有@RequestMapping中
 */
@ControllerAdvice
public class ExceptionHandle {

    private static final Logger log = LoggerFactory.getLogger(ExceptionHandle.class);
    /**
     * 全局异常捕获，将系统抛出的异常封装成我们自定义的格式
     * @ExceptionHandler 指定需要捕获的异常类
     * 由于类上没有@RestController，所以方法上需要标记@ResponseBody
     * 也可以使用@RestControllerAdvice代替，这样就不需要标记@ResponseBody
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e){
        if(e instanceof LuckymoneyException){
            LuckymoneyException luckymoneyException = (LuckymoneyException) e;
            return ResultUtils.error(luckymoneyException.getCode(),luckymoneyException.getMessage());
        }
        log.error("SYSTEM ERROR: ", e);
        return ResultUtils.error(ResultEnum.UNKNOWN_ERROR);
    }
}
